<template>
  <div class="mapContainer" :id="containerStyle">
    <!-- 照片大图预览 -->
    <transition name="fade">
      <div class="bigPic" v-show="bigPicShow">
        <span @click="bigPicShow = false">×</span>
        <p>{{ picName }}</p>
        <img :src="picSrc" />
      </div>
    </transition>
    <!--Leaflet地图容器-->
    <div id="leafletContainer"></div>
    <!-- 标注绘制确认窗 -->
    <el-dialog
      v-model="confrimWindowShow1"
      title="是否确认使用此标注？"
      width="100%"
      :close-on-click-modal="false"
      :show-close="false"
    >
      <template #footer>
        <span class="dialog-footer">
          <el-button type="danger" @click="cancel">取消</el-button>
          <el-button type="success" @click="confrim"> 确认 </el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 多边形查询确认窗 -->
    <el-dialog
      v-model="confrimWindowShow2"
      title="是否进行查询？"
      width="100%"
      :close-on-click-modal="false"
      :show-close="false"
    >
      <template #footer>
        <span class="dialog-footer">
          <el-button type="danger" @click="cancelSelect">取消</el-button>
          <el-button type="success" @click="confrimSelect"> 确认 </el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 点选查询类型选择窗 -->
    <el-dialog
      v-model="confrimWindowShow3"
      title="请选择要素查询的类型"
      width="100%"
      :close-on-click-modal="false"
      :show-close="false"
    >
      <template #footer>
        <span class="dialog-footer">
          <el-button
            type="primary"
            @click="
              selectType = 'drawing';
              confrimWindowShow3 = false;
            "
            >标绘图层</el-button
          >
          <el-button
            type="primary"
            @click="
              selectType = 'landuse';
              confrimWindowShow3 = false;
            "
          >
            用地图层
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
/* eslint-disable */
import { getCurrentInstance, onMounted } from "vue";
import * as esri from "esri-leaflet";
import "leaflet/dist/leaflet.css";
import L from "leaflet";
import "@supermap/iclient-leaflet";
import icon from "leaflet/dist/images/marker-icon.png";
import iconShadow from "leaflet/dist/images/marker-shadow.png";
import pubsub from "pubsub-js";
import axios from "axios";
import { useRouter } from "vue-router";

import message from "@/components/Message/showMessage";
import urlList from "@/store/urlList.json";

export default {
  name: "LeafletMap",
  data() {
    return {
      imgPath: "示例图例.png",
      legendHoverShow: false,
      subList: [],
      confrimWindowShow1: false,
      confrimWindowShow2: false,
      confrimWindowShow3: false,
      containerStyle: "mapStyle",
      pickPoint: [],
      polygonRangeList: [],
      mapDrawingList: [],
      picSrc: "",
      picName: "",
      bigPicShow: false,
      selectType: "",
    };
  },
  setup() {
    // 在setup中使用data的数据
    const { proxy } = getCurrentInstance();
    // 创建路由对象
    const router = useRouter();
    // 主颜色
    const mainColor = "#c0372f";
    // icon样式载入
    const DefaultIcon = L.icon({
      iconUrl: icon,
      shadowUrl: iconShadow,
      iconAnchor: [13.5, 40],
    });
    L.Marker.prototype.options.icon = DefaultIcon;
    // 当前图上图层列表
    let layerList = [];
    // 当前标准类型
    let drawingType = "";
    // 点标注对象
    let markerPoint = {};
    // 面标注类
    var rectangleMeasure = {
      points: null,
      geometry: null,
      lines: null,
      tempLines: null,
      node: null,
      drawPolygon: function () {
        // 鼠标样式修改
        L.DomUtil.addClass(_map._container, "leaflet-cursor-pointer");
        if (rectangleMeasure.tempLines) {
          rectangleMeasure.removePolygon();
        }
        _map.doubleClickZoom.disable();
        rectangleMeasure.lines = new L.polyline([], {
          color: mainColor,
        });
        rectangleMeasure.tempLines = new L.polyline([], {
          dashArray: 5,
          color: mainColor,
        });
        rectangleMeasure.points = [];
        rectangleMeasure.geometry = [];
        _map.on("click", rectangleMeasure.onClick); //点击地图
        _map.on("dblclick", rectangleMeasure.onDoubleClick); //双击地图
      },
      onClick: function (e) {
        rectangleMeasure.points.push([e.latlng.lat, e.latlng.lng]);
        rectangleMeasure.lines.addLatLng(e.latlng);
        _map.addLayer(rectangleMeasure.tempLines);
        _map.addLayer(rectangleMeasure.lines);
        rectangleMeasure.node = L.circle(e.latlng, {
          radius: 1,
          color: mainColor,
          fillColor: mainColor,
          fillOpacity: 1,
        });
        _map.addLayer(rectangleMeasure.node);
        rectangleMeasure.geometry.push(rectangleMeasure.node);
        proxy.polygonRangeList = rectangleMeasure.points;
      },
      onDoubleClick: function (e) {
        rectangleMeasure.geometry.push(
          L.polygon(rectangleMeasure.points, {
            color: mainColor,
            fillColor: mainColor,
            fillOpacity: 0.5,
          }).addTo(_map)
        );
        rectangleMeasure.points = [];
        rectangleMeasure.node = null;
        _map.doubleClickZoom.enable();
        // message("面标注绘制完成");
        proxy.confrimWindowShow1 = true;
      },
      offDraw: function () {
        _map.off("click", rectangleMeasure.onClick); //点击地图
        _map.off("dblclick", rectangleMeasure.onDoubleClick);
        L.DomUtil.removeClass(_map._container, "leaflet-cursor-pointer");
      },
      removePolygon: function () {
        for (let geometry of rectangleMeasure.geometry) {
          geometry.remove();
        }
        rectangleMeasure.geometry = [];
        rectangleMeasure.points = [];
        rectangleMeasure.node = null;
        _map.removeLayer(rectangleMeasure.lines);
        _map.removeLayer(rectangleMeasure.tempLines);
        rectangleMeasure.lines = new L.polyline([]);
      },
    };
    // 框选查询类
    var polygonSelect = {
      points: null,
      geometry: null,
      lines: null,
      tempLines: null,
      node: null,
      drawPolygon: function () {
        // 鼠标样式修改
        L.DomUtil.addClass(_map._container, "leaflet-cursor-pointer");
        if (polygonSelect.tempLines) {
          polygonSelect.removePolygon();
        }
        _map.doubleClickZoom.disable();
        polygonSelect.lines = new L.polyline([], {
          color: mainColor,
        });
        polygonSelect.tempLines = new L.polyline([], {
          dashArray: 5,
          color: mainColor,
        });
        polygonSelect.points = [];
        polygonSelect.geometry = [];
        _map.on("click", polygonSelect.onClick); //点击地图
        _map.on("dblclick", polygonSelect.onDoubleClick); //双击地图
      },
      onClick: function (e) {
        polygonSelect.points.push([e.latlng.lat, e.latlng.lng]);
        polygonSelect.lines.addLatLng(e.latlng);
        _map.addLayer(polygonSelect.tempLines);
        _map.addLayer(polygonSelect.lines);
        polygonSelect.node = L.circle(e.latlng, {
          radius: 1,
          color: mainColor,
          fillColor: mainColor,
          fillOpacity: 1,
        });
        _map.addLayer(polygonSelect.node);
        polygonSelect.geometry.push(polygonSelect.node);
        proxy.polygonRangeList = polygonSelect.points;
      },
      onDoubleClick: function (e) {
        polygonSelect.geometry.push(
          L.polygon(polygonSelect.points, {
            color: mainColor,
            fillColor: mainColor,
            fillOpacity: 0.5,
          }).addTo(_map)
        );
        polygonSelect.points = [];
        polygonSelect.node = null;
        _map.doubleClickZoom.enable();
        // message("查询多边形绘制完成");
        proxy.confrimWindowShow2 = true;
      },
      offDraw: function () {
        _map.off("click", polygonSelect.onClick); //点击地图
        _map.off("dblclick", polygonSelect.onDoubleClick);
        L.DomUtil.removeClass(_map._container, "leaflet-cursor-pointer");
      },
      removePolygon: function () {
        for (let geometry of polygonSelect.geometry) {
          geometry.remove();
        }
        polygonSelect.geometry = [];
        polygonSelect.points = [];
        polygonSelect.node = null;
        _map.removeLayer(polygonSelect.lines);
        _map.removeLayer(polygonSelect.tempLines);
        polygonSelect.lines = new L.polyline([]);
      },
    };
    // 临时绘制面
    let tempPolygon = [];

    // 实例被挂载后调用
    onMounted(() => {
      initMap();
      subscribeList();
      addMapDrawing();
    });

    //订阅列表
    function subscribeList() {
      proxy.subList.push(
        // 地图显示控制
        pubsub.subscribe("basicalMapChange", (n, data) => {
          // 打开地图
          if (data.isChecked) {
            addMap(data.nodeData);
          }
          // 关闭地图
          else {
            layerList.forEach((element) => {
              if (element.label === data.nodeData.label) {
                _map.removeLayer(element.layer);
                layerList.splice(layerList.indexOf(element), 1);
              }
            });
          }
        }),
        // 图层透明度变化
        pubsub.subscribe("opacityChange", (n, data) => {
          layerList.forEach((element) => {
            if (element.label === data.label) {
              element.layer.setOpacity(1 - data.opacity / 100);
            }
          });
        }),
        // 清除全部标注
        pubsub.subscribe("clearAllDrawing", (n, data) => {
          proxy.mapDrawingList.forEach((element) => {
            _map.removeLayer(element.drawingMarker || element.drawingPolygon);
            _map.removeLayer(element.drawingPopup);
          });
        }),
        // 标注显示控制
        pubsub.subscribe("drawingChange", (n, data) => {
          // 打开标注
          if (data.isChecked) {
            console.log(data);
            // 添加图层
            proxy.mapDrawingList.forEach((element) => {
              if (element.name === data.nodeData.label) {
                console.log(element);
                _map.setView(element.centerPoint, 7);
                (element.drawingMarker || element.drawingPolygon).addTo(_map);
                element.drawingPopup.addTo(_map);
              }
            });
            // 消息提示
            // message(data.nodeData.label + "标注已加载");
          }
          // 关闭标注
          else {
            proxy.mapDrawingList.forEach((element) => {
              if (element.name === data.nodeData.label) {
                // console.log(element);
                _map.removeLayer(
                  element.drawingMarker || element.drawingPolygon
                );
                _map.removeLayer(element.drawingPopup);
              }
            });
            // 消息提示
            // message(data.nodeData.label + "标注已关闭");
          }
        }),
        // 点标注
        pubsub.subscribe("pointDrawing", (n, data) => {
          // 开启
          if (data.isUsed) {
            drawingType = "point";
            // 鼠标样式修改
            L.DomUtil.addClass(_map._container, "leaflet-cursor-pointer");
            // 地图操作
            _map.on("click", (e) => {
              // 清除旧标记
              if (markerPoint != {}) _map.removeLayer(markerPoint);
              let pickPoint = e.latlng;
              proxy.pickPoint = [
                pickPoint.lat.toFixed(2),
                pickPoint.lng.toFixed(2),
              ];
              // console.log(proxy.pickPoint);
              // 添加标记
              markerPoint = L.marker(pickPoint);
              markerPoint.addTo(_map);
              // 询问窗唤醒
              proxy.confrimWindowShow1 = true;
            });
            // 消息提示
            // message("开启点标注");
          }
          // 关闭
          else {
            // 移除绑定事件
            _map.off("click");
            // 鼠标样式修改
            L.DomUtil.removeClass(_map._container, "leaflet-cursor-pointer");
            // 移除图标
            if (markerPoint != {}) _map.removeLayer(markerPoint);
            // 消息提示
            // message("关闭点标注", "error");
          }
        }),
        // 地图视角移动
        pubsub.subscribe("setView", (n, data) => {
          _map.setView(data, 7);
        }),
        // 返回地图路由守卫
        pubsub.subscribe("toMap", (n, data) => {
          proxy.containerStyle = "mapStyle";
          if (proxy.pickPoint.length != 0) _map.setView(proxy.pickPoint, 7);
          proxy["confrimWindowShow" + data.flag] = true;
          // 地图刷新
          window.location.reload();
        }),
        // 跳转至详细信息窗口路由守卫
        pubsub.subscribe("toDetail", (n, data) => {
          proxy.containerStyle = "dataStyle";
        }),
        // 清除标注
        pubsub.subscribe("clearDrawing", (n, data) => {
          if (markerPoint != {}) _map.removeLayer(markerPoint);
          if (rectangleMeasure.points != null) rectangleMeasure.removePolygon();
          if (polygonSelect.points != null) polygonSelect.removePolygon();
          message("已清除标注");
          pubsub.publish("toolFinished", {
            titleIndex: 0,
            childIndex: 2,
          });
        }),
        // 绘制面
        pubsub.subscribe("polygonDrawing", (n, data) => {
          if (data.isUsed) {
            drawingType = "polygon";
            rectangleMeasure.drawPolygon();
            // message("已开启绘制");
          } else {
            rectangleMeasure.removePolygon();
            rectangleMeasure.offDraw();
            // message("已结束绘制");
          }
        }),
        // 框选查询
        pubsub.subscribe("polygonSelect", (n, data) => {
          if (data.isUsed) {
            // message("框选查询已开启");
            polygonSelect.drawPolygon();
          } else {
            // message("框选查询已关闭");
            polygonSelect.offDraw();
            polygonSelect.removePolygon();
          }
        }),
        // 点选查询
        pubsub.subscribe("pointSelect", (n, data) => {
          if (data.isUsed) {
            // 鼠标样式修改
            L.DomUtil.addClass(_map._container, "leaflet-cursor-pointer");
            // 选择窗弹出
            proxy.confrimWindowShow3 = true;
            // 地图点击事件绑定
            _map.on("click", (e) => {
              let selectedPoint = [e.latlng.lat, e.latlng.lng];
              // 处理点选坐标
              switch (proxy.selectType) {
                // 未指定
                case "":
                  message("请先选择查询类型", "error");
                  return;
                // 查询标绘图层
                case "drawing":
                  _map.setView([e.latlng.lat, e.latlng.lng + 90], 7);
                  drawingClickSearch(selectedPoint);
                  break;
                // 查询用地图层
                case "landuse":
                  _map.setView([e.latlng.lat, e.latlng.lng + 90], 7);
                  landuseClickSearch(selectedPoint);
                  break;
              }
            });
          } else {
            proxy.confrimWindowShow3 = false;
            // 鼠标样式恢复
            L.DomUtil.removeClass(_map._container, "leaflet-cursor-pointer");
            _map.off("click");
          }
        }),
        // 仅显示框选结果标注
        pubsub.subscribe("mapDrawingReset", (n, data) => {
          proxy.mapDrawingList.forEach((drawing) => {
            let isSelected = false;
            data.forEach((element) => {
              if (element.id === drawing.id) {
                isSelected = true;
              }
            });
            if (!isSelected) {
              // console.log(drawing);
              _map.removeLayer(drawing.drawingPolygon || drawing.drawingMarker);
              _map.removeLayer(drawing.drawingPopup);
            }
          });
        }),
        // 详细返回框选结果页面
        pubsub.subscribe("toSelectResult", (n, data) => {
          proxy.containerStyle = "mapStyle";
        }),
        // 地图重载
        pubsub.subscribe("mapReset", () => {
          proxy.mapDrawingList.forEach((drawing) => {
            _map.removeLayer(drawing.drawingPolygon || drawing.drawingMarker);
            (drawing.drawingPolygon || drawing.drawingMarker).addTo(_map);
            _map.removeLayer(drawing.drawingPopup);
            drawing.drawingPopup.addTo(_map);
          });
        }),
        // 照片大图
        pubsub.subscribe("bigPic", (n, data) => {
          proxy.bigPicShow = true;
          proxy.picSrc = data.picSrc;
          proxy.picName = data.name;
        }),
        // 信息更新地图样式更新
        pubsub.subscribe("toUpdate", () => {
          proxy.containerStyle = "inputStyle";
        }),
        // 用地查询结果边界绘制
        pubsub.subscribe("drawLanduseBound", (n, data) => {
          if (data.isOn) {
            tempPolygon.forEach((element) => {
              _map.removeLayer(element);
            });
            let list = data.list;
            list.forEach((l) => {
              let pointList = [];
              for (let i = 0; i < l.length; i++) {
                pointList.push(l[i].reverse());
              }
              tempPolygon.push(
                L.polygon(pointList, {
                  color: "white",
                  fillColor: "white",
                  fillOpacity: 0,
                }).addTo(_map)
              );
            });

            // list.forEach((l) => {
            //   for (let i = 0; i < l.length; i++) {
            //     pointList.push(l[i].reverse());
            //   }
            //   tempPolygon.push(
            //     L.polygon(pointList, {
            //       color: "red",
            //       fillColor: "red",
            //       fillOpacity: 0,
            //     }).addTo(_map)
            //   );
            // });
          } else {
            tempPolygon.forEach((element) => {
              _map.removeLayer(element);
            });
          }
        }),
        // 上传CAD路由跳转
        pubsub.subscribe("uploadCAD", () => {
          router.push({
            path: "/mapLayout/uploadCAD",
          });
        })
      );
    }

    //创建地图
    function initMap() {
      // 准备gz2000坐标系参数
      const scaleDenominators = [
        4622333.68, 2311166.84, 1155583.42, 577791.71, 288895.85, 144447.93,
        72223.96, 36111.98, 18055.99, 9028.0, 4514.0, 2257.0, 1128.5, 564.25,
      ];

      const bounds = {
        top: 318728.1875,
        left: 6225.9501953125,
        bottom: 165313.25,
        leftBottom: {
          x: 6225.9501953125,
          y: 165313.25,
        },
        right: 118680.125,
        rightTop: {
          x: 118680.125,
          y: 318728.1875,
        },
      };

      // 构建gz2000坐标系
      const mapcrs = L.CRS.NonEarthCRS({
        bounds: L.bounds(
          [bounds.left, bounds.bottom],
          [bounds.right, bounds.top]
        ),
        resolutions: [
          264.5838625010584, 132.2919312505292, 52.91677250021167,
          26.458386250105836, 13.229193125052918, 6.614596562526459,
          2.6458386250105836, 0.5291677250021167, 0.13229193125052918,
        ],
        origin: L.point(-5623200.0, 10002100),
        scaleDenominators: scaleDenominators,
      });

      // 在gz2000坐标系上创建地图
      let map = L.map("leafletContainer", {
        center: [182495.579, 66784.853],
        crs: mapcrs,
        preferCanvas: true,
        maxZoom: 8,
        minZoom: 3,
        zoom: 7,
        zoomControl: false, // 隐藏缩放控件
        attributionControl: false, // 隐藏信息控件
        logoControl: false, // 隐藏logo图标
        closePopupOnClick: false,
      });

      // 暴露地图对象为公共变量
      window._map = map;
      // 加载底图
      esri
        .tiledMapLayer({
          url: "http://192.168.81.247:6080/arcgis/rest/services/%E4%BE%9B%E7%94%B5%E5%B1%80/202305/MapServer",
          useCors: false,
        })
        .addTo(_map);
    }

    // 添加地图图层
    function addMap(data) {
      // 读取并加载图层
      let layer = esri
        .tiledMapLayer({
          url: urlList.mapURL + data.label + "/MapServer",
          useCors: false,
          opacity: 0.8,
        })
        .addTo(_map);

      // 存入图层数组
      layerList.push({
        label: data.label,
        isLanduse: data.isLanduse,
        layer,
      });
      // console.log(layerList);
    }

    // 加载自定义标注图层
    function addMapDrawing() {
      axios({
        method: "get",
        url: urlList.serverURL + "getPositionData",
      }).then((res) => {
        proxy.mapDrawingList = [];
        res.data.result.forEach((element) => {
          // console.log(element);
          switch (element.featureType) {
            case "point":
              loadPointDrawing(element);
              break;
            case "polygon":
              loadPolygonDrawing(element);
              break;
          }
        });
        // 图层列表更新
        pubsub.publish("mapControllRenew", proxy.mapDrawingList);
        // 视图移动
        _map.setView([182495.579, 66784.853], 7);
      });
    }

    // 加载点标注
    function loadPointDrawing(element) {
      // 读取坐标值
      let part1 = element.geometry.split(",")[0].replace(/[^0-9]/g, "");
      let part2 = element.geometry.split(",")[1].replace(/[^0-9]/g, "");
      let lat = parseInt(part1 / 100) + (part1 % 100) / 100;
      let lng = parseInt(part2 / 100) + (part2 % 100) / 100;
      //  图上加载marker
      let drawingMarker = L.marker([lat, lng]);
      drawingMarker.addTo(_map);
      // 图上加载popup
      let drawingPopup = L.popup({
        autoClose: false,
      })
        .setLatLng([lat, lng])
        .setContent(
          `<div style='color:` +
            mainColor +
            `;text-align:center'>` +
            element.name +
            `</div>`
        );
      drawingPopup.addTo(_map);
      // 存入数组
      proxy.mapDrawingList.push({
        id: element.id,
        type: element.featureType,
        name: element.name,
        geometry: [lat, lng],
        centerPoint: [lat, lng],
        drawingMarker,
        drawingPopup,
      });
    }

    // 加载面标注
    function loadPolygonDrawing(element) {
      // console.log(element);
      let list = element.geometry.split(",");
      // 读取坐标值
      let pointList = [];
      for (let i = 0; i < list.length; i++) {
        if (list[i + 1] != undefined && list[i] > 100000)
          pointList.push([Number(list[i]), Number(list[i + 1])]);
      }
      // console.log(pointList);
      // 图上绘制
      let drawingPolygon = L.polygon(pointList, {
        color: mainColor,
        fillColor: mainColor,
        fillOpacity: 0.5,
      });
      drawingPolygon.addTo(_map);
      // 绘制中心标识
      let drawingPopup = L.popup({
        autoClose: false,
      })
        .setLatLng(calculatingCenter(list))
        .setContent(
          `<div style='color:` +
            mainColor +
            `;text-align:center''>` +
            element.name +
            `</div>`
        );
      drawingPopup.addTo(_map);
      // 存入数组
      proxy.mapDrawingList.push({
        id: element.id,
        type: element.featureType,
        name: element.name,
        geometry: pointList,
        centerPoint: calculatingCenter(list),
        drawingPolygon,
        drawingPopup,
      });
    }

    function calculatingCenter(list) {
      let latSum = 0;
      let lngSum = 0;
      for (let i = 0; i < list.length; i++) {
        if (i % 2 === 0) {
          latSum += Number(list[i]);
        } else {
          lngSum += Number(list[i]);
        }
      }
      return [latSum / (list.length / 2), lngSum / (list.length / 2)];
    }

    // 不使用当前标注
    function cancel() {
      // 关闭窗口
      proxy.confrimWindowShow1 = false;
      // 消除标记
      _map.removeLayer(markerPoint);
      // message("已清除标注");
    }

    // 使用当前标注
    function confrim() {
      // 关闭窗口
      proxy.confrimWindowShow1 = false;
      // 地图样式更新
      proxy.containerStyle = "inputStyle";
      // 鼠标样式恢复
      L.DomUtil.removeClass(_map._container, "leaflet-cursor-pointer");
      // 关闭标注功能
      switch (drawingType) {
        case "point":
          _map.off("click");
          // 路由跳转
          router.push({
            path: "/mapLayout/input",
            query: {
              geometry: proxy.pickPoint.toString(),
              type: "point",
            },
          });
          break;
        case "polygon":
          console.log(proxy.polygonRangeList);
          // 路由跳转
          router.push({
            path: "/mapLayout/input",
            query: {
              geometry: proxy.polygonRangeList.toString(),
              type: "polygon",
            },
          });
          break;
      }
    }

    // 取消查询
    function cancelSelect() {
      polygonSelect.removePolygon();
      proxy.confrimWindowShow2 = false;
    }

    // 确认查询
    function confrimSelect() {
      let pointList = [];
      polygonSelect.geometry.forEach((element) => {
        if (element._latlng)
          pointList.push([element._latlng.lat, element._latlng.lng]);
      });
      pointList.pop();
      router.push({
        path: "/mapLayout/selectResult",
        query: {
          geometry: pointList.toString(),
          type: "polygon",
          shunt: "polygonSelection",
        },
      });
      proxy.confrimWindowShow2 = false;
      // polygonSelect.removePolygon();
      polygonSelect.offDraw();
    }

    // 查询所有标绘的中心点
    function getCenter() {
      return axios({
        method: "get",
        url: urlList.serverURL + "getCenter",
      });
    }

    // 查询点集中最近的点
    function nearestPoint(selectedPoint, pointList) {
      let minDistance = 99999999999;
      let minPoint = {};
      pointList.forEach((element) => {
        let point = JSON.parse(element.centerpoint);
        let distance = Math.sqrt(
          Math.pow(selectedPoint[0] - point[0], 2) +
            Math.pow(selectedPoint[1] - point[1], 2)
        );
        if (distance < minDistance) {
          minDistance = distance;
          minPoint = element;
        }
      });
      console.log(minPoint);
      return minPoint;
    }

    // 标绘点选查询
    function drawingClickSearch(selectedPoint) {
      L.DomUtil.removeClass(_map._container, "leaflet-cursor-pointer");
      // _map.off("click");
      // 读取所有标绘的中心点
      getCenter().then((res) => {
        // 计算最近的标绘
        let point = nearestPoint(selectedPoint, res.data.result);
        console.log(point);
        // 路由跳转
        router.push({
          path: "/mapLayout/detail",
          query: {
            id: point.id,
            type: "mapDrawingSelect",
          },
        });
        // 数据发送
        pubsub.publish("drawingDetailData", { id: point.id });
      });
    }

    // 要素点选查询
    function landuseClickSearch(selectedPoint) {
      let landuseLayerList = [];
      layerList.forEach((layer) => {
        // 排除非用地图层
        if (layer.isLanduse) landuseLayerList.push(layer.label);
      });
      // console.log(landuseLayerList);
      if (landuseLayerList.length === 0) {
        message("地图中没有用地图层", "error");
        return;
      }
      // 发送至选择界面
      router.push({
        path: "/mapLayout/selectResult",
        query: {
          layerList: JSON.stringify(landuseLayerList),
          selectedPoint,
          shunt: "landuseSelection",
        },
      });
      pubsub.publish("landuseClickSearch");
    }

    return {
      cancel,
      confrim,
      cancelSelect,
      confrimSelect,
    };
  },
  beforeDestroy() {
    this.subList.forEach((element) => {
      pubsub.unsubscribe(element);
    });
  },
  beforeRouteLeave() {
    this.subList.forEach((element) => {
      pubsub.unsubscribe(element);
    });
  },
};
</script>

<style lang="less" scoped>
.fade-enter-active {
  transition: all 0.3s;
}
.fade-leave-active {
  transition: all 0.3s;
  transform: translateX(100%);
}
.fade-enter-from,
.fade-leave-to {
  transition: 0.3s;
  transform: translateX(100%);
}
.bigPic {
  position: absolute;
  top: 0.5%;
  right: 0.5%;
  width: 50%;
  height: 50%;
  z-index: 9999;
  background-color: white;
  border-radius: 5px;
  box-shadow: 0px 0 7px 0.1px #8d8d8d;
  display: flex;
  justify-content: center;
  align-items: center;
  > p {
    position: absolute;
    top: 2%;
    left: 2%;
  }
  > span {
    font-weight: bold;
    font-size: 180%;
    display: block;
    position: absolute;
    top: 0.5%;
    right: 1.5%;
  }
  > img {
    max-height: 90%;
  }
}
.mapContainer {
  height: 94%;
  background-color: white;
  padding: 0.2%;
  margin-right: 0.25%;
  float: right;
  position: relative;
  top: 5.5%;
  border-radius: 5px;
  > #leafletContainer {
    width: 100%;
    height: 100%;
    border-radius: 5px;
  }
}

#mapStyle {
  width: 84.25%;
  // left: 15.5%;
}

#inputStyle {
  width: 50%;
  // right: -49.75%;
}

#dataStyle {
  width: 69%;
  left: -15.25%;
}

.leaflet-cursor-pointer {
  cursor: crosshair;
}

.confrimWindow {
  background-color: white;
  width: 300px;
  height: 200px;
  position: absolute;
  z-index: 9999999;
  right: 0%;
  top: 10%;
}
.leaflet-container{
  background-color: white;
}
</style>